/*

pages.product.listing.js

Author: Byron Salau
Contributors:

This file is part of Blanc

Licenced under the MIT License (MIT)
 
Copyright (C) 2011 - 2012 Codagenic Pty. Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

Blanc.Pages.Products.Listing =
{

	config: 
	{
		type: "loadmore",
		replaceHistory: false,
		loadBtnTemplate: function ()
		{
			return "<a class=\"ui-button\">Load More</a>";
		},
		itemTemplate: function (data)
		{
			var source = $("#productItemTemplate").html(),
				template = Handlebars.compile(source);
						
			return template(data);
		}
	},

	/**
	* Constructor
	*/
	init: function ()
	{
		Blanc.Controls.SubNavigation.init();

		this.CategoryController.init($('#codagenicCategory'), Blanc.Pages.Products.Listing.config);
	},

	CategoryController:
	{
		init: function ($element, options)
		{
			var self = this,

			defaults =                  // default options
			{
				type: "LoadMore",       // "LoadMore", "LazyLoad", "None"
				replaceHistroy: true,   // Uses window.replaceHistory API to retain ajaxed products
				lazyLoadOffset: 20,      // Trigger load 20px from bottom

				// Templates
				itemTemplate: function (item)
				{
					return "<li><a href=\"" + item.url + "\">" + item.title + "</a></li>";
				},

				loadBtnTemplate: function ()
				{
					return "<a>Load More</a>";
				},

				// Callbacks
				onPagerLoad: null,
				onPagerFinish: null
			};

			// the plugin's final properties are the merged default and
			// user-provided options (if any)
			self.options = $.extend({}, defaults, options);

			if (self.options.type.toLowerCase() === "none")
			{
				return; // Exit
			}

			var $pager = $('#pager'),
				totalPages = $element.data('total-pages'),
				categoryId = $element.data('category-id'),
				pageSize = $element.data('page-size') || 10,
				page = $element.data('page') + 1 || 1;

			if (totalPages === "undefined" || categoryId === "undefined")
			{
				throw new Error("ERROR: 'data-total-pages' and/or 'data-category-id' attributes not specified on element");
			}

			//Hide fallback pager
			$pager.hide();

			if (totalPages > 1)
			{
				// Paging available

				var $btnLoadMore,
					$products = $element.find('ul.product-listing'),
					_successHandler = function (data)
					{
						// Build new products HTML
						var html = "";
						for (var i = 0; i < data.products.length; i++)
						{
							html += self.options.itemTemplate(data.products[i]);
						}

						// Inject new products into DOM
						$products.append(html);

						// Update history if available and configured
						if (window.history.replaceState && self.options.replaceHistroy)
						{
							window.history.replaceState($products.html(), window.document.title, window.document.URL);
						}
					},
					_failureHandler = function (data)
					{
						// TODO: Make a more usuable error
						throw new Error(data);
					},
					_load = function (_callback)
					{
						// Public callback
						if ($.isFunction(self.options.onPagerLoad))
						{
							self.options.onPagerLoad({
								page: page,
								pageSize: pageSize,
								totalPages: totalPages
							});
						}

						// Add loading class
						$('body').addClass('codagenic-loading');

						// Hit the API service
						var service = new Codagenic.ProductDataAccess();

						service.listProducts(categoryId, pageSize, page, function(data)
						{
							_successHandler(data);

							// Remove loading class
							$('body').removeClass('codagenic-loading');

							// Public callback
							if ($.isFunction(self.options.onPagerFinish))
							{
								self.options.onPagerFinish({
									pageNumber: page,
									pageSize: pageSize,
									totalPages: totalPages
								});
							}

							// Private callback
							if ($.isFunction(_callback))
							{
								_callback();
							}

							// Increment Page Count
							page++;

							// Validate page count
							if (page > totalPages)
							{
								if (self.options.type.toLowerCase() === "loadmore")
								{
									// Remove load more button
									$btnLoadMore.remove();
								}
								else if (self.options.type.toLowerCase() === "lazyload")
								{
									//Remove the scroll event
									$(window).unbind("scroll.codagenic");
								}
							}

						}, _failureHandler);

					};

				if (self.options.type.toLowerCase() === "loadmore")
				{
					// Check if returned button is a template or an jquery object

					if (typeof self.options.loadBtnTemplate() === "string")
					{
						$btnLoadMore = $(self.options.loadBtnTemplate());


						// Check if we have a pager control
						if ($pager.length < 0)
						{
							$element.append($btnLoadMore);
						}
						else
						{
							$pager.after($btnLoadMore);
						}

						$btnLoadMore.wrap("<div class='load-more' />");
					}
					else if (typeof self.options.loadBtnTemplate() === "object")
					{
						//test its a jquery object
						if (self.options.loadBtnTemplate().jquery)
						{
							// it's (probably) a jQuery object
							$btnLoadMore = self.options.loadBtnTemplate();
						}
						else
						{
							// it's not
							throw new Error(".codagenic(\"setCategory\") Unexpected loadBtnTemplate");
						}
					}
					else
					{
						throw new Error(".codagenic(\"setCategory\") Unexpected loadBtnTemplate");
					}

					// Event handler
					$btnLoadMore.on("click", function (e)
					{
						// Load products
						_load();

						// Stop event propogation
						e.preventDefault();
					});

				}
				else if (self.options.type.toLowerCase() === "lazyload")
				{
					var _locked = false;

					// Set up scroll event listner
					$(window).bind("scroll.codagenic", function ()
					{
						if ($(window).scrollTop() + $(window).height() > $(window.document).height() - self.options.lazyLoadOffset)
						{
							_locked = true;
							_load(function ()
							{
								_locked = false;
							});
						}
					});
				}

				// Handle history pop state if replace history configured
				if (self.options.replaceHistroy)
				{
					window.onpopstate = function (e)
					{
						if (window.history.state !== null)
						{
							$element.find('ul.product-listing').html(window.history.state);
						}
					};
				}

			}
		}
	}


};